package com.fingard.dsp.bank.directbank.jstzrcb01;

import java.io.File;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.net.WebRequest;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import static com.fingard.io.FileHelper.*;
import static com.fingard.text.StringHelper.trimEndFileSp;

/**
 * @author dicke
 * @date 2018/9/18 13:59
 */
public class JSTZRCB01BatPayRec extends JSTZRCB01Base implements IBatPayRec {
    /**
     * 批量代付提交
     *
     * @param p_req1988 批量代付请求对象
     * @return 批量代付响应对象
     * @throws Exception
     */
    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        RetAtsBatPayRec retAts =  new RetAtsBatPayRec(p_req1988.reqHeader);
        retAts.writeStart();

        String filePath  = getBankConfig().getValueAsString("IDTransformDirectory");
        if(!existFile(filePath)){
            mkdir(filePath);
        }

        String PostScriptPath = getBankConfig().getValueAsString("PostScriptPath");
        if(!existFile(PostScriptPath)){
            mkdir(PostScriptPath);
        }

        XmlTextWriter xmlWriter =  new XmlTextWriter();
        JSTZRCB01Header header =  new JSTZRCB01Header();
        header.transTime = DateHelper.convertToDateExtra(p_req1988.reqHeader.transTime);
        String OpName = "B2EBatchTransfer";
        header.transCode = OpName;
        header.reqSeqNo = p_req1988.reqHeader.reqSeqID;
        xmlWriter.autoFormat = false;
        writeCommonHead(xmlWriter,header);

        xmlWriter.writeStartElement("Body");
        xmlWriter.writeStartElement("List");
        StringBuilder content = new StringBuilder();
        StringBuilder PostScriptContent  = new StringBuilder();
        while(p_req1988.readRecord()){
            XElement tmpElement  = new XElement("Map","");

            String TransferType ;
            if(notSameBank.equals(p_req1988.readedDetail.sameBnk)){
                TransferType = "002";
            } else {
                TransferType = "001";
            }

            tmpElement.addChild(new XElement("TransferType",TransferType));
            tmpElement.addChild(new XElement("PayerAcNo",p_req1988.readedDetail.payAct));
            tmpElement.addChild(new XElement("PayerAcName",p_req1988.readedDetail.payName));
            //付方账户类型取默认
            tmpElement.addChild(new XElement("PayerBankAcType",this.getBankConfig().getMapValueByKey("cardType", "00")));
            String currency = convertCurToBank(p_req1988.readedDetail.payCur);
            tmpElement.addChild(new XElement("PayerCurrency",currency));
            //加急标志 默认 1
            tmpElement.addChild(new XElement("Priority","1"));
            tmpElement.addChild(new XElement("PayeeAcNo",p_req1988.readedDetail.recAct));
            tmpElement.addChild(new XElement("PayeeAcName",p_req1988.readedDetail.recName));
            tmpElement.addChild(new XElement("PayeeCurrency",currency));
            String cardType = p_req1988.readedDetail.cardType;
            if(StringHelper.isNullOrEmpty(cardType)) {
                cardType = "00";
            }
            cardType = this.getBankConfig().getMapValueByKey("cardType", cardType);
            tmpElement.addChild(new XElement("PayeeBankAcType",cardType));
            tmpElement.addChild(new XElement("Amount",p_req1988.readedDetail.payAmount));
            //同行代发
            if(sameBank.equals(p_req1988.readedDetail.sameBnk)) {
                tmpElement.addChild(new XElement("UnionDeptId", ""));
                tmpElement.addChild(new XElement("PayeeBankName", ""));
                tmpElement.addChild(new XElement("PayeeAddr", ""));
            }
            else{
                tmpElement.addChild(new XElement("UnionDeptId", p_req1988.readedDetail.cnapsCode));
                tmpElement.addChild(new XElement("PayeeBankName", p_req1988.readedDetail.recBankName));
                tmpElement.addChild(new XElement("PayeeAddr", p_req1988.readedDetail.recBankLocation));
            }
            tmpElement.addChild(new XElement("Remark",p_req1988.readedDetail.abstractATS));

            xmlWriter.writeXElement(tmpElement);
            PostScriptContent.append(p_req1988.readedDetail.askNumber+"|");
        }

        xmlWriter.writeEndDocument();

        String PostScriptName = trimEndFileSp(PostScriptPath) + File.separator + p_req1988.reqBatchNO + "_postScript.txt";
        WriteBankLogLn("写入流水号映射码位置：" + PostScriptName);
        WriteBankLogLn("写入流水号文件内容："+ PostScriptContent.toString());
        writeFile(PostScriptName,PostScriptContent.toString(),"GBK");
        content.append(xmlWriter.toXmlString());
        String fileName = trimEndFileSp(filePath) + File.separator + p_req1988.reqBatchNO + ".xml";
        WriteBankLogLn("写入批付映射码位置：" + fileName);
        WriteBankLogLn("写入批付文件内容："+ content.toString());
        writeFile(fileName,content.toString(),"GBK");

        String[] retStrArr = sendToBank(xmlWriter.toXmlString(),"uploadFile",p_req1988.reqBatchNO + ".xml");

        if(retStrArr[0].length() == 0){
            StringBuilder tmpSbMsg = new StringBuilder();
            XmlTextReader tmpBkReader = loadBankRespXmlReader(retStrArr[1], tmpSbMsg);
            retAts.reqSeqID = p_req1988.reqBatchNO;
            if(tmpBkReader != null){
                String tmpRetCode = tmpBkReader.getFirstText("/Message/Head/IBSReturnCode");
                String tmpRetInfo = tmpBkReader.getFirstText("/Message/Head/IBSReturnMsg");
                if(BANK_RET_RIGHT_CODE.equals(tmpRetCode)){
                    retAts.respCode = "0";
                    retAts.respInfo = tmpRetInfo;
                    retAts.transState = tmpRetCode ;
                    retAts.payInfoCode  = tmpRetCode;
                }
                else{
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpRetInfo);
                }
            }
            else{
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(tmpSbMsg.toString());
            }
        }
        else{
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(retStrArr[1].toString());
        }
        retAts.writeRetToATS();
        return retAts;
    }

    /**
     * 批量代付状态查询
     *
     * @param p_req1998 批量代付查询请求对象
     * @return 批量代付响应对象
     * @throws Exception
     */
    @Override
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        RetAtsQryBatPayRec retAts  = new RetAtsQryBatPayRec(p_req1998.reqHeader);
        retAts.writeStart();
        String reqBatchNO = p_req1998.reqBatchNO;
        String filePath =  getBankConfig().getValueAsString("IDTransformDirectory");
        String batchPayfile = filePath + File.separator + reqBatchNO + ".xml";
        if(!existFile(batchPayfile)){
            retAts.respCode = "-1";
            retAts.respInfo = "不存在对应的请求序列号或对应交易失败,请检查对应文件夹";
            retAts.writeEnd();
            return retAts;
        }
        String postScriptPath  = getBankConfig().getValueAsString("PostScriptPath");
        String postScriptFile = postScriptPath + File.separator + reqBatchNO + "_postScript.txt";
        if(!existFile(postScriptFile)){
            retAts.respCode = "-1";
            retAts.respInfo = "不存在对应的对账码,请检查对应文件夹";
            retAts.writeEnd();
            return retAts;
        }

        String EachPageNum = getBankConfig().getValueAsString("EachPageNum");
        int pageNum = Integer.parseInt(EachPageNum);
        int totalPage = Integer.parseInt(p_req1998.totalNum) / pageNum;
        if (Integer.parseInt(p_req1998.totalNum) % pageNum != 0) {
            totalPage++;
        }
        int startNumber = -1;
        int recordNumber = -1;
        for (int j = 1; j <= totalPage; j++) {
            startNumber = pageNum*(j-1)+1;
            if(j != totalPage) {
                recordNumber = pageNum;
            } else {
                recordNumber = Integer.parseInt(p_req1998.totalNum) - startNumber +1;
            }

            //<editor-fold desc="分页循环查询结果">
            XmlTextWriter xmlWriter =  new XmlTextWriter();
            JSTZRCB01Header header =  new JSTZRCB01Header();
            header.transTime = DateHelper.convertToDateExtra(p_req1998.reqHeader.transTime);
            String OpName = "B2EAgentSalaryQryDetail";
            header.transCode = OpName;
            header.reqSeqNo = p_req1998.reqHeader.reqSeqID;
            xmlWriter.autoFormat = false;
            writeCommonHead(xmlWriter,header);

            XElement tmpElement  = new XElement("Body","");
            tmpElement.addChild(new XElement("HistoryERPJnlNo", String.format("%016d", header.reqSeqNo)));

            tmpElement.addChild(new XElement("currentIndex",startNumber+""));
            tmpElement.addChild(new XElement("pageSize",recordNumber+""));
            xmlWriter.writeXElement(tmpElement);
            xmlWriter.writeEndDocument();

            String PostScriptName = postScriptPath + File.separator + p_req1998.reqBatchNO + "_postScript.txt";
            WriteBankLogLn("读取对账码文件位置：" + PostScriptName);
            String PostScriptContent = readFileText(PostScriptName,"GBK");
            WriteBankLogLn("读取对账码文件内容" + PostScriptContent);
            String[] PostScripts  = PostScriptContent.split("\\|");

            String[] retStrArr = sendToBank(xmlWriter.toXmlString(),OpName);

            if(retStrArr[0].length() == 0){
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(retStrArr[1], tmpSbMsg);
                if(tmpBkReader != null){
                    String tmpRetCode = tmpBkReader.getFirstText("/Message/Head/IBSReturnCode");
                    String tmpRetInfo = tmpBkReader.getFirstText("/Message/Head/IBSReturnMsg");
                    if(BANK_RET_RIGHT_CODE.equals(tmpRetCode)){
                        retAts.respCode = "0";
                        String AllDetail =  tmpBkReader.getSimpleText("FileContent");
                        String[] details =  AllDetail.split("\n");
                        for (int i = 0 ; i < details.length ; i++){
                            RetAtsBatPayRecDetail retAtsDetail =  new RetAtsBatPayRecDetail();
                            String[] PayResult = details[i].split("\\|");
                            String AccountNumber =  PayResult[0];
                            String AccountName =  PayResult[1];
                            String Amount = PayResult[2];
                            String Result =  PayResult[3];
                            String PayInfo = PayResult[4];
                            retAtsDetail.result =  tmpRetCode + "+" + Result;
                            retAtsDetail.memo  = PayInfo;
                            retAtsDetail.payInfoCode =  tmpRetCode + "+" + Result;
                            retAtsDetail.recAct = AccountNumber;
                            retAtsDetail.recName = AccountName;
                            retAtsDetail.payAmount = Amount;
                            //银行返回对账码没有埋入，需从文件中映射
                            retAtsDetail.postScript  = PostScripts[i+(j-1)*pageNum];
                            retAts.writeRetDetail(retAtsDetail);
                        }
                    }
                    else{
                        retAts.writeRespCode("-1");
                        retAts.writeRespInfo(tmpRetInfo);
                        break;
                    }
                }
                else{
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpSbMsg.toString());
                    break;

                }
            }
            else{
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(retStrArr[1].toString());
                break;
            }
            //</editor-fold>
        }
        retAts.writeEnd();
        return retAts;
    }

    /**
     * 批量代扣提交
     *
     * @param p_req9188 批量代扣请求对象
     * @return 批量代扣响应对象
     * @throws Exception
     */
    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        return null;
    }

    /**
     * 批量代收状态查询
     *
     * @param p_req9198 批量代扣查询请求对象
     * @return 批量代扣查询响应对象
     * @throws Exception
     */
    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        return null;
    }

    protected String[] sendToBank(String pReqStr,String opName,String fileName) throws Exception{
        //http://ProxyIP:ProxyPort/ent/uploadFile.do?userPassword=123456&SIGDATA=1&fileName=123.xml&delete=1&transCode=123
        WriteBankLogStep2(pReqStr);
        String[] retStr = new String[]{"",""};
        String tmpAddrUrl = "http://" + bankFront.serverIP + ":" + bankFront.serverPort+"/ent/" + opName + ".do?userPassword="+
                bankFront.loginPasswd+"&SIGDATA=1&fileName="+fileName+"&delete=1&transCode=123";
        String sendInfo = pReqStr;
        WriteBankLogLn("2.提交银行的地址：" + tmpAddrUrl);
        WebRequest tmpWebRequest = new WebRequest(tmpAddrUrl);
        tmpWebRequest.setConnectTimeout(10000);
        tmpWebRequest.setRequestProperty("User-Agent", "API");

        byte[] tmpUpBytes = sendInfo.getBytes(getCharset());
        retStr = tmpWebRequest.upload(tmpUpBytes, getCharset());

        WriteBankLogStep3(retStr[1]);
        return retStr;
    }
}
